package com.example.usercenter.sys.web;

import com.alibaba.fastjson.JSONObject;
import com.example.usercenter.common.base.ResponseData;
import com.example.usercenter.sys.entity.*;
import com.example.usercenter.sys.service.OrgService;
import com.example.usercenter.sys.service.UserGroupService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.usercenter.common.base.BaseRestController;
import com.example.usercenter.common.base.BaseService;
import com.example.usercenter.sys.service.RoleService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/role")
public class RoleController extends BaseRestController<Role, Long> {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserGroupService userGroupService;
    @Autowired
    private OrgService orgService;

    protected BaseService<Role, Long> getService(){
            return roleService;
    }

    @Override
    @PreAuthorize("hasAuthority('ROLE')")
    public ResponseData get(@PathVariable("id") Long id) {
        return super.get(id);
    }

    @Override
    @PreAuthorize("hasAuthority('ROLE')")
    public ResponseData save(@RequestBody Role entity) {
        ResponseData checkResult = checkGroupAndOrg(entity);
        if(checkResult!=null)
            return checkResult;
        return super.save(entity);
    }

    private ResponseData checkGroupAndOrg(Role entity){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        //判断用户组
        long groupId = entity.getGroup().getId();
        UserGroup group = userGroupService.get(groupId);
        if(group.getPath().indexOf("/"+user.getGroup().getId()+"/")<0){
            return ResponseData.fail("非法用户组设值");
        }
        //判断组织
        long orgId = entity.getOrg().getId();
        Org org = orgService.get(orgId);
        boolean inOrgTree = false;
        for(OrgUser ou : user.getOrgUsers()){
            if(group.isChildAuth()){
                if(org.getPath().indexOf("/"+ou.getOrgId()+"/")>=0){
                    inOrgTree = true;
                    break;
                }
            }
            if(user.getGroup().isPeerAuth()){
                if(ou.getOrgId() == orgId){
                    inOrgTree = true;
                    break;
                }
            }
        }
        if(!inOrgTree){
            return ResponseData.fail("非法组织设值");
        }
        return null;
    }

    @Override
    @PreAuthorize("hasAuthority('ROLE')")
    public ResponseData update(@RequestBody Role entity) {
        ResponseData checkResult = checkGroupAndOrg(entity);
        if(checkResult!=null)
            return checkResult;
        return super.update(entity);
    }

    @Override
    @PreAuthorize("hasAuthority('ROLE')")
    public ResponseData delete(@PathVariable("id") Long id) {
        return super.delete(id);
    }

    @Override
    @PreAuthorize("hasAuthority('ROLE')")
    public ResponseData page(@RequestBody JSONObject params) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        List<Org> orgs = orgService.getOrgsByUser(user, "ROLE");
        if(orgs.size()==0){
            return ResponseData.fail("查询角色列表时，搜索用户可查看组织范围为空，查询角色列表失败");
        }
        //获取组织ID
        List<Long> orgIds = orgs.stream().map(org -> org.getId()).collect(Collectors.toList());
        params.put("orgIds", orgIds);
        return super.page(params);
    }

    @Override
    @Secured({"ROLE", "USER"})
    public ResponseData query(@RequestBody JSONObject params) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) auth.getPrincipal();
        Set<Org> orgs = new HashSet<Org>();
        return super.query(params);
    }

    @PreAuthorize("hasAuthority('ROLE')")
    @Override
    public ResponseData exists(@RequestBody JSONObject params) {
        return super.exists(params);
    }
}